# coding=utf-8

import re

from lib.perforce2git import ExecCmd
from lib.perforce2git import HasPerforcePendingChanges

from lib.perforce2git import GetGitCurrentBranch
from lib.perforce2git import GetPerforceChangesAfterChange
from lib.perforce2git import TransferChangeFromP4ToGit

from lib.perforce2git import SetPerforceDepot
from lib.perforce2git import SetWorkspaceDir
from lib.perforce2git import SetPerforceClient

# 全局变量

# perforce 服务器代码库路径
PERFORCE_DEPOT = '//depot/stg/PerfTools/Microbench/'

# perforce 和 git 命令执行的工作目录（本地代码库路径）
WORKSPACE_DIR = r'D:\dev\p4\stg_ugl\stg\PerfTools\Microbench'

# perforce 的当前工作目录
P4_CLIENT = "chanchen_ugl_dev"

# 返回 git 当前分支已经同步的 change 号
def GetGitSyncChange():
    args = "git log --oneline -1"
    out, err = ExecCmd(args, True)
    m = re.search("(.+) Change (\d+)", out, re.M)
    assert m
    rev, result = m.group(1), m.group(2)

    return rev, result

# 检查 git 的当前分支是否为指定分支（默认为 master 分支）。如果不是，提示并退出程序。
def CheckGitCurrentBranch(expectedBranch, currBranch):
    if currBranch != expectedBranch:
        print("Current branch is `%s`. Must be in branch `%s` to run this tool." % (currBranch, expectedBranch))
        exit(-1)

# Rebase new changes on master branch to linux, dev branches
def RebaseBranches(rev):
    branches = ["linux", "dev"]
    for branch in branches:
        ExecCmd(['git', 'checkout', branch])

        # 记录当前 rev
        args = "git log --oneline -1"
        out, err = ExecCmd(args, True)
        m = re.search("(.+) Change (\d+)", out, re.M)
        assert m
        oldRev = m.group(1)

        ExecCmd(['git', 'reset', '--hard', 'master'])
        ExecCmd(['git', 'rebase', '--onto', oldRev, rev, branch])

if __name__ == "__main__":
    SetPerforceDepot(PERFORCE_DEPOT)
    SetWorkspaceDir(WORKSPACE_DIR)
    SetPerforceClient(P4_CLIENT)

    branch = GetGitCurrentBranch()
    CheckGitCurrentBranch('master', branch)

    rev, change = GetGitSyncChange()

    if HasPerforcePendingChanges():
        exit(-1)
    changes = GetPerforceChangesAfterChange(change)
    for change in changes:
        TransferChangeFromP4ToGit(change)

    RebaseBranches(rev)
